package com.elong.businesstravel.modules.orders.adapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.ImageUtil;
import com.android.support.jhf.utils.MobileUtils;
import com.android.support.jhf.utils.ToolUtils;
import com.android.support.jhf.viewpagercanscroll.CanScrollViewPager;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.recorder.Recorder;
import com.elong.businesstravel.base.recorder.Recorder.OnStateChangedListener;
import com.elong.businesstravel.base.umeng.socialize.CustomShareDialog;
import com.elong.businesstravel.base.uploadpic.UploadPic;
import com.elong.businesstravel.entitys.HotelDocs;
import com.elong.businesstravel.entitys.OrderInfo;
import com.elong.businesstravel.modules.home.hotel.hotelshow.HotelDetailActivity;
import com.elong.businesstravel.modules.home.hotel.hotelshow.HotelLocationMapActivity;
import com.elong.businesstravel.modules.orders.SendRecordCommentActivity;
import com.elong.businesstravel.modules.orders.view.OrdersView;
import com.elong.businesstravel.protocol.order.*;
import com.umeng.socialize.media.CircleShareContent;
import com.umeng.socialize.media.MailShareContent;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.SmsShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.WeiXinShareContent;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.view.PagerAdapter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * 我的订单viewpager adapter
 * 
 * @author lenovo
 * 
 */
public class OrdersPagerAdapter extends PagerAdapter {

	private static final String SAVE_VOICE_PATH = UploadPic.SDCARD_ROOT_PATH
			+ "/" + UploadPic.CLT + "/" + Recorder.RECORD + "/";

	private List<OrderInfo> mOrderInfos;
	private Context mContext;
	private CustomShareDialog mCustomShareDialog;
	private CanScrollViewPager mCanScrollViewPager;

	private AnimationDrawable mAnimationDrawable;
	private ImageView lastPlayAnimImageView;
	private Recorder mRecorder;
	private Bitmap mShareBitmap;

	public OrdersPagerAdapter(Context context, List<OrderInfo> orderInfos,
			CanScrollViewPager canScrollViewPager, Recorder recorder) {
		this.mOrderInfos = orderInfos;// 构造方法，参数是我们的页卡，这样比较方便。
		mContext = context;
		mShareBitmap = ImageUtil.drawable2Bitmap(mContext.getResources()
				.getDrawable(R.drawable.ic_share));
		mCanScrollViewPager = canScrollViewPager;
		mRecorder = recorder;
		mRecorder.setOnStateChangedListener(new OnStateChangedListener() {

			@Override
			public void onStateChanged(int state) {

			}

			@Override
			public void onError(int error) {

			}

			@Override
			public void onCompletion() {
				if (null != mAnimationDrawable) {
					mCanScrollViewPager.setCanScroll(true);
					mAnimationDrawable.stop();
					if (null != lastPlayAnimImageView)
						lastPlayAnimImageView.setImageDrawable(mContext
								.getResources().getDrawable(
										R.anim.record_play_wait_xml));
				}
			}
		});
	}

	public void stopPlayback() {
		if (null != mRecorder)
			mRecorder.stopPlayback();
		if (null != lastPlayAnimImageView)
			lastPlayAnimImageView.setImageDrawable(mContext.getResources()
					.getDrawable(R.anim.record_play_wait_xml));
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);// 删除页卡
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) { // 这个方法用来实例化页卡
		final OrderInfo orderInfo = mOrderInfos.get(position);
		final OrdersView view = new OrdersView(mContext);

		if ("1".equals(orderInfo.canvoice)) {
			// 可以点评
			// if (orderInfo.cancel.equals("0")) {//TODO:取消订单时发送录音，测试用
			if ("0".equals(orderInfo.isvoice)) {
				// 没有录音，显示录音按钮
				view.setHotelMapButtonVisibility(View.GONE);
				view.setCommentVisibility(View.VISIBLE);
				view.setPlayRecordLayoutVisibility(View.GONE);
			} else if ("1".equals(orderInfo.isvoice)) {
				// 有录音显示播放按钮
				view.setHotelMapButtonVisibility(View.GONE);
				view.setCommentVisibility(View.GONE);
				view.setPlayRecordLayoutVisibility(View.VISIBLE);
			}
		} else {
			// 不能点评
			view.setHotelMapButtonVisibility(View.VISIBLE);
			view.setCommentVisibility(View.GONE);
			view.setPlayRecordLayoutVisibility(View.GONE);
			if ("0".equals(orderInfo.isvoice)) {
				// // 没有录音，显示录音按钮
				// view.setHotelMapButtonVisibility(View.GONE);
				// view.setCommentVisibility(View.VISIBLE);
				// view.setPlayRecordLayoutVisibility(View.GONE);
			} else if ("1".equals(orderInfo.isvoice)) {
				// 有录音显示播放按钮
				view.setHotelMapButtonVisibility(View.GONE);
				view.setCommentVisibility(View.GONE);
				view.setPlayRecordLayoutVisibility(View.VISIBLE);
			}
		}

		// view.setCommentVisibility(View.VISIBLE);
		// view.setPlayRecordLayoutVisibility(View.GONE);
		// view.setHotelMapButtonVisibility(View.GONE);

		view.setCommentOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext,
						SendRecordCommentActivity.class);
				intent.putExtra("orderinfo", orderInfo);
				((Activity) mContext).startActivityForResult(intent, 0);
			}
		});

		final ImageView playRecordImageView = view.getPlayAnimImageView();
		int lenght = 0;
		try {
			lenght = Integer.parseInt(orderInfo.voicetime);
		} catch (Exception e) {
		}
		view.setRecordLenghtTextView(lenght + "”");
		view.setPlayRecordLayout(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				downLoadVoice(orderInfo, view);
			}
		});
		view.setOrdersNumberTextView(orderInfo.elongorderid);
		view.setOrdersStatusTextView(orderInfo.orderstate);
		view.setTimeTextView(orderInfo.createtime);
		view.setHotelNameTextView(orderInfo.hotelname,
				new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						HotelDocs hotelDocs = new HotelDocs();
						hotelDocs.hotelName = orderInfo.hotelname;
						hotelDocs.hotelId = orderInfo.elonghotelid;
						hotelDocs.hotelAddress = orderInfo.address;
						Intent intent = new Intent(mContext,
								HotelDetailActivity.class);
						intent.putExtra("hotelDocs", hotelDocs);
						mContext.startActivity(intent);
					}
				});
		float totalprice = 0F;
		try {
			totalprice = Float.parseFloat(orderInfo.totalprice);
		} catch (Exception e) {
		}
		String moneyString = "";
		if (totalprice % 1.0 == 0) {
			moneyString = "￥" + (int) (totalprice);
		} else {
			moneyString = "￥" + totalprice;
		}
		SpannableStringBuilder moneySpannable = new SpannableStringBuilder(
				moneyString);
		moneySpannable.setSpan(new ForegroundColorSpan(mContext.getResources()
				.getColor(R.color.list_gray_text_color)), 0, 1,
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		float moneySize = mContext.getResources().getDimension(
				R.dimen.list_text_small_size);
		moneySpannable.setSpan(new AbsoluteSizeSpan((int) moneySize), 0, 1,
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		view.setHotelMoneyTextView(moneySpannable);
		view.fanMoneyTextView(orderInfo.totalbonus);
		view.setRoomTypeTextView(orderInfo.roomname);
		view.setRoomNumTextView(orderInfo.roomnum + "间");
		view.setHotelAddressTextView(orderInfo.address);
		String phone = orderInfo.phone;
		try {
			phone = phone.replace("，", ",");
			phone = phone.split(",")[0];
			phone = ToolUtils.getNumberFromString(phone);
		} catch (Exception e) {
			e.printStackTrace();
		}
		final String callPhoneString = phone;
		view.setHotelPhoneTextView(orderInfo.phone, new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				final CustomAlertDialog customAlertDialog = new CustomAlertDialog(
						mContext, R.style.CustomAlertDialog);
				customAlertDialog.setMessage(orderInfo.phone);
				customAlertDialog.setLeftButton("拨打", new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						MobileUtils.callPhoneActivity(mContext,
								callPhoneString, Intent.ACTION_VIEW);
					}
				});
				customAlertDialog.setRightButton("取消", new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
				customAlertDialog.show();

			}
		});
		view.setNameTextView(orderInfo.contactname);
		String contactmobile = orderInfo.contactmobile;
		try {
			contactmobile = contactmobile.replace("，", ",");
			contactmobile = contactmobile.split(",")[0];
			contactmobile = ToolUtils.getNumberFromString(contactmobile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		view.setNamePhoneTextView(contactmobile);
		view.setInTimeTextView(orderInfo.startdate);
		view.setOutTimeTextView(orderInfo.enddate);
		view.setReservedToTextView(orderInfo.latestarrival);

		if (orderInfo.notice.equals("")) {
			view.setButtonLayoutVisibility(View.VISIBLE);
			if (orderInfo.cancel.equals("0")) {
				// 已取消
				view.setCancelOrderVisibility(View.GONE);
			} else {
				view.setCancelOrderVisibility(View.VISIBLE);
			}
			view.setCancelOrderOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					showDialog(view, orderInfo);
				}
			});
			view.setHotelMapOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(mContext,
							HotelLocationMapActivity.class);
					intent.putExtra("GoogleLng", orderInfo.googlelon);
					intent.putExtra("GoogleLat", orderInfo.googlelat);
					intent.putExtra("HotelName", orderInfo.hotelname);
					mContext.startActivity(intent);
				}
			});
			view.setNoticeLayoutVisibility(View.GONE);
		} else {
			view.setButtonLayoutVisibility(View.GONE);
			view.setNoticeLayoutVisibility(View.VISIBLE);
			view.setNoticeTextView(orderInfo.notice);
		}

		view.setShareOrderTextView(new OnClickListener() {

			@Override
			public void onClick(View v) {
				shareOrder(orderInfo, "订单分享", "把这个订单发送给您的好友", 0);
			}
		});

		view.setShareLocationTextView(new OnClickListener() {

			@Override
			public void onClick(View v) {
				shareOrder(orderInfo, "订单分享", "把这个订单发送给您的好友", 1);
			}
		});

		container.addView(view);
		return view;
	}

	@Override
	public int getCount() {
		return mOrderInfos.size();// 返回页卡的数量
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;// 官方提示这样写
	}

	/**
	 * notifyDataSetChanged好使
	 */
	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	private void showDialog(final OrdersView view, final OrderInfo orderInfo) {

		final CustomAlertDialog customAlertDialog = new CustomAlertDialog(
				mContext, R.style.CustomAlertDialog);
		customAlertDialog.setMessage("是否取消当前订单");
		customAlertDialog.setLeftButton("是", new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				cancelOrder(view, orderInfo);
			}
		});
		customAlertDialog.setRightButton("否", new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});
		customAlertDialog.show();

	}

	private void cancelOrder(final OrdersView view, final OrderInfo orderInfo) {
		NetworkClient.getNetworkClient().PostRequest(
				new CancleOrderRequest(mContext, orderInfo.orderid),
				new CancleOrderResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerToastUI.getHandlerToastUI(mContext, "订单取消成功");

						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								orderInfo.cancel = "0";
								orderInfo.orderstate = "已取消";

								// 刷新当前界面
								view.setButtonLayoutVisibility(View.VISIBLE);
								view.setCancelOrderVisibility(View.GONE);
								view.setOrdersStatusTextView(orderInfo.orderstate);
							}
						});
					}
				});
	}

	/**
	 * 订单分享
	 * 
	 * @param orderInfo
	 * @param titleString
	 * @param descString
	 * @param flag
	 *            0 分享订单，1 分享位置
	 */
	private void shareOrder(OrderInfo orderInfo, String titleString,
			String descString, int flag) {

		String shareTitleString = "";
		String shareContentString = "";

		if (0 == flag) {
			shareTitleString = orderInfo.mShareInfo.title;
			shareContentString = orderInfo.mShareInfo.content;
		} else if (1 == flag) {
			shareTitleString = orderInfo.mShareInfo.title;
			shareContentString = "位于" + orderInfo.address + "电话"
					+ orderInfo.phone;
		}

		UMImage umImage = new UMImage(mContext, orderInfo.mShareInfo.imageurl);

		WeiXinShareContent weiXinShareContent = new WeiXinShareContent();
		weiXinShareContent.setShareContent(shareContentString);
		weiXinShareContent.setTitle(shareTitleString);
		if (umImage.isUrlMedia()) {
			weiXinShareContent.setShareImage(umImage);
		} else {
			weiXinShareContent
					.setShareImage(new UMImage(mContext, mShareBitmap));
		}
		weiXinShareContent.setTargetUrl(orderInfo.mShareInfo.shareurl);
		weiXinShareContent.setAppWebSite(orderInfo.mShareInfo.shareurl);

		CircleShareContent circleShareContent = new CircleShareContent();
		circleShareContent.setShareContent(shareContentString);
		circleShareContent.setTitle(shareTitleString);
		if (umImage.isUrlMedia()) {
			circleShareContent.setShareImage(umImage);
		} else {
			circleShareContent
					.setShareImage(new UMImage(mContext, mShareBitmap));
		}
		circleShareContent.setTargetUrl(orderInfo.mShareInfo.shareurl);
		circleShareContent.setAppWebSite(orderInfo.mShareInfo.shareurl);

		SinaShareContent sinaShareContent = new SinaShareContent();
		sinaShareContent.setShareContent(shareTitleString + shareContentString
				+ ",详情点击" + orderInfo.mShareInfo.shareurl);
		// sinaShareContent.setTitle(mShareContentString);
		// sinaShareContent.setShareImage(new UMImage(mContext,
		// orderInfo.mShareInfo.imageurl));
		// if (umImage.isUrlMedia()) {
		// sinaShareContent.setShareImage(umImage);
		// } else {
		sinaShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		// }

		// TencentWbShareContent tencentWbShareContent = new
		// TencentWbShareContent();
		// tencentWbShareContent.setShareContent(mShareTitleString
		// + mShareContentString + mShareUrlString);
		// // tencentWbShareContent.setTitle(mShareContentString);
		// tencentWbShareContent
		// .setShareImage(new UMImage(mContext, mShareBitmap));
		MailShareContent mailShareContent = new MailShareContent();
		mailShareContent.setShareContent(shareTitleString + shareContentString
				+ ",详情点击" + orderInfo.mShareInfo.shareurl);
		// mailShareContent.setTitle(mShareTitleString + mShareContentString +
		// mShareUrlString);
		// mailShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		// mailShareContent.setTargetUrl(mShareUrlString);
		// mailShareContent.setAppWebSite(mShareUrlString);

		QQShareContent qqShareContent = new QQShareContent();
		qqShareContent.setShareContent(shareContentString);
		qqShareContent.setTitle(shareTitleString);
		qqShareContent.setTargetUrl(orderInfo.mShareInfo.shareurl);
		qqShareContent.setAppWebSite(orderInfo.mShareInfo.shareurl);
		if (umImage.isUrlMedia()) {
			qqShareContent.setShareImage(umImage);
		} else {
			qqShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		}

		SmsShareContent smsShareContent = new SmsShareContent();
		smsShareContent.setShareContent(shareTitleString + shareContentString
				+ ",详情点击" + orderInfo.mShareInfo.shareurl);
		// smsShareContent.setTitle(mShareContentString);
		// smsShareContent.setShareImage(new UMImage(mContext, mShareBitmap));

		mCustomShareDialog = new CustomShareDialog(mContext,
				com.android.support.jhf.R.style.DialogFromDownToUp);
		mCustomShareDialog.setTitleMessage(titleString, descString);
		mCustomShareDialog.setShareContent(weiXinShareContent,
				circleShareContent, sinaShareContent, mailShareContent,
				qqShareContent, smsShareContent);
		mCustomShareDialog.show();
	}

	private void downLoadVoice(final OrderInfo orderInfo, final OrdersView view) {
		String tempPicUrlString = orderInfo.voiceurl;
		if (tempPicUrlString.startsWith("http://")) {

		} else {
			tempPicUrlString = "http://" + tempPicUrlString;
		}
		final String picUrlString = tempPicUrlString;

		// 判断缓存
		String fname = picUrlString
				.substring(picUrlString.lastIndexOf("/") + 1);
		fname = SAVE_VOICE_PATH + fname;
		File recordFile = new File(fname);
		if (recordFile.exists()) {
			// 有缓存播放
			playRecorder(fname, view);
			return;
		}

		NetworkClient.getNetworkClient().GetRequest(
				new DownLoadRequest(mContext, picUrlString),
				new DownLoadResponse() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] binaryData, HttpResponse response) {
						super.onSuccess(statusCode, headers, binaryData,
								response);
						String fname = picUrlString.substring(picUrlString
								.lastIndexOf("/") + 1);
						fname = SAVE_VOICE_PATH + fname;
						final String tempFname = fname;
						final boolean result = saveRecorder(binaryData,
								new File(fname));
						if (!result) {
							HandlerToastUI
									.getHandlerToastUI(mContext, "下载录音失败");
							return;
						}
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								playRecorder(tempFname, view);
							}
						});
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {
					}
				});
	}

	private void stopRecorderAnim(String pathString, OrdersView view) {
		final ImageView playRecordImageView = view.getPlayAnimImageView();
		mAnimationDrawable = (AnimationDrawable) playRecordImageView
				.getDrawable();
		if (null != mAnimationDrawable && mAnimationDrawable.isRunning()
				&& null != lastPlayAnimImageView) {
			mAnimationDrawable.stop();
			if (null != lastPlayAnimImageView)
				lastPlayAnimImageView.setImageDrawable(mContext.getResources()
						.getDrawable(R.anim.record_play_wait_xml));
		}
	}

	public void stopRecorderAnim() {
		if (null != lastPlayAnimImageView) {
			mAnimationDrawable = (AnimationDrawable) lastPlayAnimImageView
					.getDrawable();
			if (null != mAnimationDrawable && mAnimationDrawable.isRunning()
					&& null != lastPlayAnimImageView) {
				mAnimationDrawable.stop();
				if (null != lastPlayAnimImageView)
					lastPlayAnimImageView.setImageDrawable(mContext
							.getResources().getDrawable(
									R.anim.record_play_wait_xml));
			}
		}
	}

	private void playRecorder(String pathString, OrdersView view) {

		stopRecorderAnim(pathString, view);

		if (Recorder.PLAYING_STATE == mRecorder.getState()) {
			mRecorder.stopPlayback();
			mCanScrollViewPager.setCanScroll(true);
			return;
		} else {
			mRecorder.startPlayback(pathString);
		}

		final ImageView playRecordImageView = view.getPlayAnimImageView();
		mAnimationDrawable = (AnimationDrawable) playRecordImageView
				.getDrawable();
		mAnimationDrawable.start();
		mCanScrollViewPager.setCanScroll(false);
		lastPlayAnimImageView = playRecordImageView;
	}

	private boolean saveRecorder(byte[] recorderByte, File file) {
		boolean result = true;
		File pathFile = new File(file.getAbsolutePath().substring(0,
				file.getAbsolutePath().lastIndexOf("/")));
		try {
			if (!pathFile.exists()) {
				try {
					pathFile.mkdirs();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (!file.exists()) {

				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			try {
				fileOutputStream.write(recorderByte, 0, recorderByte.length);
				fileOutputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
				result = false;
			} finally {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			result = false;
		}
		return result;
	}
}
